<!--
 * @Descripttion: 工厂品质
 * @LastEditors: xzh
 * @LastEditTime: 2024-01-20 18:54:49
-->
<template>
  <div class="factory-container" v-loading="factoryParam.loading">
    <template v-if="factoryParam.dataArr.length > 0">
      <DataTypeList
        v-for="(data, index) in factoryParam.dataArr"
        :key="index"
        :dataType="factoryDataTypeEnum.cost"
        :dataMap="data"
        @exportData="handleExportData"
        @refresh="init($event, index)"
      />
    </template>
    <DileEmpty v-else />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRefs } from "vue";
import { factoryDataTypeEnum } from "@typings/factoryManage/index.type";
import { object_Inf } from "@/utils/typings/index.type";
import { dayjs } from "element-plus";
import DataTypeList from "../dataType-list/index.vue";
import DileEmpty from "@/components/dile-empty/index.vue";
import Dile_APi from "@/api";
import Dile_StoreAction from "@/utils/cache/store";
import Dile_Methods from "@/utils/methods";

/**
 * @Author: xzh
 * @Descripttion:工厂参数
 * @Param:
 */
let factoryParam = reactive<object_Inf>({
  loading: false,
  dataArr: [],
});

/**
 * @Author: xzh
 * @Descripttion:初始化
 * @Param:
 */
onMounted(() => {
  init();
});
/**
 * @Author: xzh
 * @Descripttion: 加载列表信息
 * @Param:
 */
let init = async (param: object_Inf = {}, index: number = -1) => {
  let { dateValue, type } = param,
    { loading, dataArr } = toRefs(factoryParam);
  try {
    loading.value = true;
    let [startDate, endDate] = (
        dateValue || [
          Dile_Methods.getDefaultToDay(),
          Dile_Methods.getDefaultToDay(),
        ]
      ).map((x: any) => dayjs(x).format("YYYY-MM-DD")),
      //获取当前工厂
      { id } = Dile_StoreAction.getCurrentFactory();
    //获取列表信息
    let data = (
      await Dile_APi.getFactoryCostList({
        startDate,
        endDate,
        orgId: id,
        type,
      })
    ).map((x: object_Inf) => ({
      ...x,
      type: `${factoryDataTypeEnum.cost}_${x.type}`,
    }));
    //判断是否单个加载
    index > -1 ? (dataArr.value[index] = data[0]) : (dataArr.value = data);
  } finally {
    loading.value = false;
  }
};
/**
 * @Author: xzh
 * @Descripttion: 导出数据
 * @Param:
 * @param {*} type
 * @param {*} dateValue
 */
let handleExportData = async ({ type, dateValue }: object_Inf) => {
  //获取时间范围
  let [startDate, endDate] = dateValue.map((x: any) =>
      dayjs(x).format("YYYY-MM-DD")
    ),
    //获取当前工厂
    { id: orgId } = Dile_StoreAction.getCurrentFactory();
  //导出成本数据
  let res = await Dile_APi.exportFactoryCostData({
    startDate,
    endDate,
    type,
    orgId,
  });
  //导出文件
  Dile_Methods.handleFile(res);
};
</script>
<style lang="scss" scoped>
.factory-container {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
</style>
